//
//  ShoppingCartViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/3.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "ShoppingCartViewController.h"
#import "ShoppingCartTableViewCell.h"
#import "BottomJieSuanView.h"
#import "BuyViewController.h"
#import "CartModel.h"
#import "GoodsDetailViewController.h"
#import "LoginViewController.h"

@interface ShoppingCartViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *cartDataArray;
@property (nonatomic, strong) NSMutableArray *btnStateArray;
@property (nonatomic, strong) NSMutableArray *selectArray;
@property (nonatomic, strong) BottomJieSuanView *bottomJieSuanV;
@property (nonatomic, assign) NSInteger isEdit;
@property (nonatomic, assign) CGFloat sumPrice;
@property (nonatomic, strong) UIImageView *cartImg;
@property (nonatomic, strong) UILabel *cartLB;

@end

@implementation ShoppingCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"购物车"];
    if (self.isTiaoZhuanType != 1) {
        self.leftBtn.hidden = YES;
    }
    self.isEdit = 0;
    [self setUpUI];
    [self getCartData];
    self.selectArray = [NSMutableArray array];
}

#pragma mark - 获取购物车数据
- (void)getCartData
{
    self.bottomJieSuanV.priceLB.text = @"￥0.00";
    [self.bottomJieSuanV.selectAllBtn setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
    self.bottomJieSuanV.selectAllBtn.selected = NO;
    [self.selectArray removeAllObjects];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=shopcart&companyid=%@&from=mobile",kServerURL,companyId] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        self.cartDataArray = [NSMutableArray array];
        self.btnStateArray = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            self.cartDataArray = [CartModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            self.cartImg.hidden = YES;
            self.cartLB.hidden = YES;
            
        } else if ([responseObject[@"status"] intValue] == 0) {
            self.cartImg.hidden = NO;
            self.cartLB.hidden = NO;
        }
        for (int i = 0; i<self.cartDataArray.count; i++) {
            [self.btnStateArray addObject:@"1"];
        }
        self.selectArray = [NSMutableArray arrayWithArray:self.cartDataArray];
        [self setFinalPrice];
        [self.bottomJieSuanV.selectAllBtn setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
        self.bottomJieSuanV.selectAllBtn.selected = YES;
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)setUpUI
{
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, rateHeight(90))];
    bgV.backgroundColor = tableViewBgColor;
    [self.view addSubview:bgV];
    
    UIButton *selectBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [selectBtn setImage:UIImageNamed(@"shopImg") forState:(UIControlStateNormal)];
    [bgV addSubview:selectBtn];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgV);
        make.size.mas_offset(CGSizeMake(rateWidth(80), rateHeight(90)));
        make.centerY.equalTo(bgV);
    }];
    UILabel *label = [UILabel labelWithText:AppName textColor:UIColorFromRGB(0x333333) fontSize:15];
    [label sizeToFit];
    [bgV addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectBtn.mas_right);
        make.centerY.equalTo(bgV);
    }];
    UIButton *editBtn = [UIButton buttonWithTitle:@"编辑" fontSize:15 titleColor:UIColorFromRGB(0x666666) background:kClearColor cornerRadius:0];
    [bgV addSubview:editBtn];
    [editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(rateWidth(100), rateHeight(90)));
        make.right.equalTo(bgV);
        make.centerY.equalTo(bgV);
    }];
    [editBtn addTarget:self action:@selector(editAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:self.tableView];
    
    BottomJieSuanView *bottomV = [[BottomJieSuanView alloc] init];
    [self.view addSubview:bottomV];
    if (self.isTiaoZhuanType != 1) {
        [bottomV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-49-SafeAreaBottomHeight);
            make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(100)));
        }];
    } else {
        [bottomV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.bottom.equalTo(self.view);
            make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(100)));
        }];
    }
    [bottomV.jieSuanBtn addTarget:self action:@selector(jieSuanAction) forControlEvents:(UIControlEventTouchUpInside)];
    [bottomV.selectAllBtn addTarget:self action:@selector(selectAll:) forControlEvents:(UIControlEventTouchUpInside)];
    self.bottomJieSuanV = bottomV;
    
    UIImageView *img = [[UIImageView alloc] init];
    img.image = UIImageNamed(@"enmShopCart");
    [img sizeToFit];
    [self.view addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    self.cartImg = img;
    self.cartImg.hidden = YES;
    
    UILabel *textLB = [UILabel labelWithText:@"购物车空空如也~" textColor:UIColorFromRGB(0x666666) fontSize:13];
    [textLB sizeToFit];
    [self.view addSubview:textLB];
    [textLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(img);
        make.top.equalTo(img.mas_bottom).offset(5);
    }];
    self.cartLB = textLB;
    self.cartLB.hidden = YES;
    
}
#pragma mark - 结算/删除
- (void)jieSuanAction
{
    if (self.isEdit == 0) {
        // 结算
        if ([[UserDefaults valueForKey:@"isLogin"] intValue] == 0) {
            // 未登录
            [self loginAction];
        } else {
            if (self.selectArray.count != 0) {
                BuyViewController *buyVC = [[BuyViewController alloc] init];
                NSMutableArray *array = [NSMutableArray array];
                for (CartModel *model in self.selectArray) {
                    [array addObject:model.CartId];
                }
                buyVC.selectIdArray = array;
                [self.navigationController pushViewController:buyVC animated:YES];
            } else {
                [TFHUD addRemindHUD:self.view message:@"请选择您要购买的商品"];
            }
        }
        
    } else if (self.isEdit == 1) {
        // 删除
        [self deleteCartGoods];
    }
}
- (void)loginAction
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    [self presentViewController:loginVC animated:YES completion:nil];
}
- (void)editAction:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.selected) {
        [btn setTitle:@"完成" forState:(UIControlStateNormal)];
        self.bottomJieSuanV.sumLB.hidden = YES;
        self.bottomJieSuanV.priceLB.hidden = YES;
        [self.bottomJieSuanV.jieSuanBtn setTitle:@"删除" forState:(UIControlStateNormal)];
        self.isEdit = 1;
    } else {
        [btn setTitle:@"编辑" forState:(UIControlStateNormal)];
        self.bottomJieSuanV.sumLB.hidden = NO;
        self.bottomJieSuanV.priceLB.hidden = NO;
        [self.bottomJieSuanV.jieSuanBtn setTitle:@"结算" forState:(UIControlStateNormal)];
        self.isEdit = 0;
    }
    [self.tableView reloadData];
}
#pragma mark - 全选
- (void)selectAll:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.selected) {
        [self.btnStateArray removeAllObjects];
        for (int i = 0; i<self.cartDataArray.count; i++) {
            [self.btnStateArray addObject:@"1"];
        }
        [btn setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
        
        self.selectArray = [NSMutableArray arrayWithArray:self.cartDataArray];
    } else {
        [self.btnStateArray removeAllObjects];
        for (int i = 0; i<self.cartDataArray.count; i++) {
            [self.btnStateArray addObject:@"0"];
        }
        [btn setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
        [self.selectArray removeAllObjects];
    }
    [self.tableView reloadData];
    [self setFinalPrice];
}
- (void)setFinalPrice
{
    self.sumPrice = 0.0;
    for (CartModel *model in self.selectArray) {
        self.sumPrice = self.sumPrice+[model.CommodityNumber intValue]*[model.CommodityXPrice floatValue];
    }
    self.bottomJieSuanV.priceLB.text = [NSString stringWithFormat:@"￥%.2f",self.sumPrice];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.isTiaoZhuanType != 1) {
        self.tabBarController.tabBar.hidden = NO;
    }
    //    [self getCartData];
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _cartDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingCartTableViewCell *cell = [[ShoppingCartTableViewCell alloc] init];
    if (_cartDataArray.count != 0) {
        CartModel *model = _cartDataArray[indexPath.row];
        [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",model.CartImg]]];
        cell.goodsNameLB.text = model.CommodityName;
        cell.describeLB.text = [NSString stringWithFormat:@"已选：%@",model.CommodityProperty];
        cell.priceLB.text = [NSString stringWithFormat:@"￥%.2f",[model.CommodityXPrice floatValue]];
        cell.numLB.text = model.CommodityNumber;
        cell.doneNumLB.text = [NSString stringWithFormat:@"×%@",model.CommodityNumber];
        
        cell.selectBtn.tag = indexPath.row;
        [cell.selectBtn addTarget:self action:@selector(selectAction:) forControlEvents:(UIControlEventTouchUpInside)];
        NSString *str = _btnStateArray[indexPath.row];
        if ([str intValue] == 0) {
            [cell.selectBtn setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
        } else if ([str intValue] == 1) {
            [cell.selectBtn setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
        }
        if (self.isEdit == 0) {
            cell.doneNumLB.hidden = NO;
            cell.editImg.hidden = YES;
            cell.jiaBtn.hidden = YES;
            cell.jianBtn.hidden = YES;
        } else if (self.isEdit == 1) {
            cell.doneNumLB.hidden = YES;
            cell.editImg.hidden = NO;
            cell.jiaBtn.hidden = NO;
            cell.jianBtn.hidden = NO;
            // 加
            cell.jiaBtn.tag = indexPath.row;
            [cell.jiaBtn addTarget:self action:@selector(numJiaAction:) forControlEvents:(UIControlEventTouchUpInside)];
            // 减
            cell.jianBtn.tag = indexPath.row;
            [cell.jianBtn addTarget:self action:@selector(numJianAction:) forControlEvents:(UIControlEventTouchUpInside)];
        }
    }
    cell.selectionStyle = NO;
    return cell;
}
- (void)numJiaAction:(UIButton *)btn
{
    if (_cartDataArray.count != 0) {
        CartModel *model = _cartDataArray[btn.tag];
        NSInteger num = [model.CommodityNumber intValue];
        num++;
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=updateshopcart&companyid=%@&id=%@&sum=%@",kServerURL,companyId,model.CartId,[NSString stringWithFormat:@"%ld",num]] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            if ([responseObject[@"status"] intValue] == 1) {
                
                model.CommodityNumber = [NSString stringWithFormat:@"%ld",num];
                [self.tableView reloadData];
                [self setFinalPrice];
            }
            
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        }];
    }
}
- (void)numJianAction:(UIButton *)btn
{
    if (_cartDataArray.count != 0) {
        CartModel *model = _cartDataArray[btn.tag];
        NSInteger num = [model.CommodityNumber intValue];
        if (num > 1) {
            num--;
            [MBProgressHUD showMessage:nil toView:self.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=updateshopcart&companyid=%@&id=%@&sum=%@",kServerURL,companyId,model.CartId,[NSString stringWithFormat:@"%ld",num]] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                if ([responseObject[@"status"] intValue] == 1) {
                    
                    model.CommodityNumber = [NSString stringWithFormat:@"%ld",num];
                    [self.tableView reloadData];
                    [self setFinalPrice];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            }];
        }
    }
}
- (void)changeGoodsNumWithNum:(NSString *)num model:(CartModel *)model
{
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=updateshopcart&companyid=%@&id=%@&sum=%@",kServerURL,companyId,model.CartId,num] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if ([responseObject[@"status"] intValue] == 1) {
            //            [self getCartData];
            
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
#pragma mark - 选择按钮
- (void)selectAction:(UIButton *)btn
{
    CartModel *model = _cartDataArray[btn.tag];
    if ([_btnStateArray[btn.tag] intValue] == 0) {
        [_btnStateArray setObject:@"1" atIndexedSubscript:btn.tag];
        [btn setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
        [self.selectArray addObject:model];
        if (![_btnStateArray containsObject:@"0"]) {
            [self.bottomJieSuanV.selectAllBtn setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
            self.bottomJieSuanV.selectAllBtn.selected = YES;
        }
    } else if ([_btnStateArray[btn.tag] intValue] == 1) {
        [_btnStateArray setObject:@"0" atIndexedSubscript:btn.tag];
        [btn setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
        [self.selectArray removeObject:model];
        if ([_btnStateArray containsObject:@"0"]) {
            [self.bottomJieSuanV.selectAllBtn setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
            self.bottomJieSuanV.selectAllBtn.selected = NO;
        }
    }
    [self setFinalPrice];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(240);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return rateHeight(10);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_cartDataArray.count != 0) {
        CartModel *model = _cartDataArray[indexPath.row];
        GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
        goodsDetailVC.contentId = model.commodityId;
        [self.navigationController pushViewController:goodsDetailVC animated:YES];
    }
}
#pragma mark - 删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (_cartDataArray.count != 0) {
            CartModel *model = _cartDataArray[indexPath.row];
            [MBProgressHUD showMessage:nil toView:self.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=deleteshopcart&companyid=%@&id=%@",kServerURL,companyId,model.CartId] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                if ([responseObject[@"status"] intValue] == 1) {
                    [self getCartData];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            }];
        }
    }
}
- (void)deleteCartGoods
{
    if (self.selectArray.count != 0) {
        [MBProgressHUD showMessage:nil toView:self.view];
        NSMutableArray *idArray = [NSMutableArray array];
        for (CartModel *model in self.selectArray) {
            [idArray addObject:model.CartId];
        }
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=deleteshopcart&companyid=%@&id=%@",kServerURL,companyId,[idArray componentsJoinedByString:@","]] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            if ([responseObject[@"status"] intValue] == 1) {
                [self getCartData];
            }
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        }];
    }
}
// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
// iOS11
- ( UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    //删除
    WeakSelf
    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        
        // 删除操作
        if (weakSelf.cartDataArray.count != 0) {
            CartModel *model = weakSelf.cartDataArray[indexPath.row];
            [MBProgressHUD showMessage:nil toView:weakSelf.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=deleteshopcart&companyid=%@&id=%@",kServerURL,companyId,model.CartId] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:weakSelf.view];
                if ([responseObject[@"status"] intValue] == 1) {
                    [weakSelf.cartDataArray removeObjectAtIndex:indexPath.row];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:weakSelf.view message:@"网络不给力..."];
            }];
        }
        
        completionHandler (YES);
        
        [self.tableView reloadData];
    }];
    //    deleteRowAction.image = [UIImage imageNamed:@"删除"];
    deleteRowAction.backgroundColor = navBarColor;
    
    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
    return config;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        WeakSelf
        if (weakSelf.isTiaoZhuanType != 1) {
            _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight+rateHeight(90), kScreenWidth, kScreenHeight-SafeAreaTopHeight-rateHeight(90)-rateHeight(100)-49-SafeAreaBottomHeight) style:(UITableViewStyleGrouped)];
        } else {
            _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight+rateHeight(90), kScreenWidth, kScreenHeight-SafeAreaTopHeight-rateHeight(90)-rateHeight(100)) style:(UITableViewStyleGrouped)];
        }
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        //        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getCartData];
        }];
        [_tableView.mj_header beginRefreshing];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
